package com.lzx.adx.report.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.DateUtils;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.cache.CommonLocalCache;
import com.lzx.adx.report.constant.ElmUnionJobConstant;
import com.lzx.adx.report.dao.EleUnionOrderDao;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.OrderRecodDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.entity.EleUnionOrderEntity;
import com.lzx.adx.report.enums.ElmCovertQttEventTypeEnums;
import com.lzx.adx.report.enums.EventTypeEnums;
import com.lzx.adx.report.model.elm.ElmUnionOrderDetail;
import com.lzx.adx.report.model.elm.ElmUnionOrderReponse;
import com.lzx.adx.report.model.elm.ElmUnionOrderReponseDetailResponse;
import com.lzx.adx.report.model.elm.ElmUnionOrderResult;
import com.lzx.adx.report.model.huawei.request.HwUploadRequest;
import com.lzx.adx.report.service.EleUnionOrderService;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.HwSecureUtil;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAlscUnionKbcpxPositiveOrderGetRequest;
import com.taobao.api.response.AlibabaAlscUnionKbcpxPositiveOrderGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Component
@EnableScheduling
@Slf4j
public class ElmUnionJob {


    @Autowired
    private EleUnionOrderService eleUnionOrderService;

    @Autowired
    private EleUnionOrderDao eleUnionOrderDao;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ReportService reportService;





    @Scheduled(cron = "0 */10 * ? * *")
    public void reportEvent() throws ApiException {
        log.info("进行饿了么联盟的订单-上报处理-begin");

        AlibabaAlscUnionKbcpxPositiveOrderGetResponse rsp = getOrderPageData(1);
        //异常情况
        if(Objects.isNull(rsp.getBizErrorCode())){
            log.error(rsp.getBody());
            return;
        }

        //正常的情况
        ElmUnionOrderReponse elmUnionOrderReponse= JSONObject.parseObject(rsp.getBody(),ElmUnionOrderReponse.class);
        //正常的情况
        ElmUnionOrderReponseDetailResponse alibabaAlscUnionKbcpxPositiveOrderGetResponse = elmUnionOrderReponse.getAlibaba_alsc_union_kbcpx_positive_order_get_response();
        ElmUnionOrderResult result = alibabaAlscUnionKbcpxPositiveOrderGetResponse.getResult();
        if(Objects.isNull(result)|| CollectionUtil.isEmpty(result.getOrder_detail_report_d_t_o())){
            return;
        }
        if(alibabaAlscUnionKbcpxPositiveOrderGetResponse.getTotal_count().equals(0)){
            return;
        }
        Integer totalPage= PageUtil.totalPage(alibabaAlscUnionKbcpxPositiveOrderGetResponse.getTotal_count(),50);
        if(totalPage>1){
            //循环取订单的数据了
            for (int i=1;i<totalPage;i++){
                AlibabaAlscUnionKbcpxPositiveOrderGetResponse newOrderPageData = getOrderPageData(i);
                ElmUnionOrderReponse newElmOrderReponse= JSONObject.parseObject(newOrderPageData.getBody(),ElmUnionOrderReponse.class);
                ElmUnionOrderReponseDetailResponse dc = newElmOrderReponse.getAlibaba_alsc_union_kbcpx_positive_order_get_response();
                ElmUnionOrderResult elmUnionOrderResult = dc.getResult();
                core(elmUnionOrderResult.getOrder_detail_report_d_t_o());
            }
        }else{
            core(result.getOrder_detail_report_d_t_o());
        }
        log.info("进行饿了么联盟的订单-上报处理-end");
    }


    private static AlibabaAlscUnionKbcpxPositiveOrderGetResponse getOrderPageData(long page) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(ElmUnionJobConstant.url, ElmUnionJobConstant.appKey, ElmUnionJobConstant.appSecret);
        AlibabaAlscUnionKbcpxPositiveOrderGetRequest req = new AlibabaAlscUnionKbcpxPositiveOrderGetRequest();
        req.setDateType(1L);
        req.setBizUnit(1L);
        req.setPageSize(50L);
        req.setPageNumber(page);
        req.setStartDate(getBeginTime());
//        req.setOrderState(2L);
        req.setIncludeUsedStoreId(false);
        AlibabaAlscUnionKbcpxPositiveOrderGetResponse rsp = client.execute(req);
        return rsp;
    }

    private void handerAqy(AccountDTO accountDTO, ReportDTO reportDTO) {
        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        String finalResultUrl=decodeUrl+"&event_type=17";
        log.info("饿了么联盟给爱奇艺 上报回传结果，完整的URl{}",finalResultUrl);
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();
        log.info("账号为{} 爱奇艺接收了饿了么联盟的回传接口，响应的结果为{}",accountDTO.getId(),result);
        JSONObject jsonObject=JSONObject.parseObject(result);
    }


    public static String getBeginTime(){
        CommonLocalCache instance = CommonLocalCache.getInstance();
        String elmUnionStime = instance.get("elmUnion_stime");
        if(StringUtils.isBlank(elmUnionStime)){
            String currentDayBegindayStime = getCurrentDayBegindayStime();
            instance.put("elmUnion_stime",getCurrentDayBegindayStime());
            return currentDayBegindayStime;
        }else {
            LocalDateTime parse = LocalDateTime.parse(elmUnionStime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if(parse.isBefore(getYesterdayStartingTime())){
                return getCurrentDayBegindayStime();
            }else{
                return elmUnionStime;
            }
        }
    }



    public  void core(List<ElmUnionOrderDetail> orderDetailReportDTO ){
        if(CollectionUtil.isNotEmpty(orderDetailReportDTO)) {
            List<EleUnionOrderEntity> data = reportMapper.toReport(orderDetailReportDTO);
            for (EleUnionOrderEntity datum : data) {
                JSONObject jsonObject=JSONObject.parseObject(datum.getExtInfo());
                String tpOrderId = jsonObject.getString("tpOrderId");
                datum.setId(tpOrderId);
                EleUnionOrderEntity eleUnionOrderEntity = eleUnionOrderService.selectById(datum.getId());
                if (Objects.nonNull(eleUnionOrderEntity)) {
                    datum.setHandStatus(eleUnionOrderEntity.getHandStatus());

                    eleUnionOrderDao.updateById(datum);
                } else {
                    datum.setHandStatus(1);
                    eleUnionOrderDao.insert(datum);
                }
                if (datum.getHandStatus().equals(2)) {
                    continue;
                }
                Date parse = DateUtils.parse(datum.getPayTime(), "yyyy-MM-dd HH:mm:ss");
                String orderTime= DateUtil.format(parse,"yyyyMMddHH");
                ReportDTO newData = reportService.getNewData(datum.getPid(), orderTime);
                if(Objects.isNull(newData)){
                    datum.setHandStatus(2);
                    eleUnionOrderDao.updateById(datum);
                    continue;
                }

                AccountDTO accountDTO = AccountLocalCache.getInstance().get(datum.getPid());
                String evenType="3";
                if(accountDTO.getProduct().equals("aqyElmu")){
                    newData.setSid(datum.getId());
                    newData.setResultType(evenType);
                    newData.setResultTime(String.valueOf(System.currentTimeMillis()));
                    reportService.updateData(newData,evenType);

                    handerAqy(accountDTO,newData);

                }else if (accountDTO.getProduct().equals("hwElmu")){

                    //更新点击和订单绑定关系
                    newData.setSid(datum.getId());
                    newData.setResultType(evenType);
                    newData.setResultTime(String.valueOf(System.currentTimeMillis()));
                    reportService.updateData(newData,evenType);

                    handerHw(accountDTO, newData);
                }else if(accountDTO.getProduct().equals("ksElmunion")){
                    newData.setSid(datum.getId());
                    newData.setResultType("3");
                    newData.setResultTime(String.valueOf(System.currentTimeMillis()));
                    reportService.updateData(newData,evenType);
                    handerKs(newData);
                }else if(accountDTO.getProduct().equals("qttElmunion")){
                    newData.setSid(datum.getId());
                    newData.setResultType(evenType);
                    newData.setResultTime(String.valueOf(System.currentTimeMillis()));
                    reportService.updateData(newData,evenType);
                    handerQtt(newData);
                }

                //更新状态为已处理
                datum.setHandStatus(2);
                eleUnionOrderDao.updateById(datum);
            }

        }
    }

    private void handerQtt(ReportDTO reportDTO) {

        Long conversion_time=Long.valueOf(reportDTO.getResultTime())/1000;

        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());

        Map<String,Object> paramsReq=new HashMap<>();
        paramsReq.put("op2", "35");
        paramsReq.put("opt_active_time",conversion_time);
        String paramss= URLUtil.buildQuery(paramsReq,StandardCharsets.UTF_8);
        String finalUrl=decodeUrl+"&"+paramss;

        String result = HttpUtil.get(finalUrl);
        JSONObject jsonObject=JSONObject.parseObject(result);
        Integer resultCode = jsonObject.getInteger("code");
    }

    private void handerHw(AccountDTO accountDTO, ReportDTO reportDTO) {

        Long conversion_time=Long.valueOf(reportDTO.getResultTime())/1000;
        HwUploadRequest hwUploadRequest=new HwUploadRequest();
        hwUploadRequest.setOaid(reportDTO.getOaid());
        hwUploadRequest.setConversion_type("paid");
        hwUploadRequest.setTimestamp(String.valueOf(System.currentTimeMillis()));
        hwUploadRequest.setCallback(reportDTO.getCallback());
        hwUploadRequest.setCampaign_id(reportDTO.getCampaignId());
        hwUploadRequest.setContent_id(reportDTO.getContentId());

        hwUploadRequest.setConversion_time(String.valueOf(conversion_time));
        hwUploadRequest.setTracking_enabled("1");
        String paramsBody = JsonUtils.toJsonString(hwUploadRequest);

        Map<String,String> header=new HashMap<>();

        header.put("Authorization", HwSecureUtil.buildAuthorizationHeader(paramsBody,accountDTO.getSspKey()));

        HttpRequest body = HttpUtil.createPost(accountDTO.getSspApiUrl()).addHeaders(header).body(paramsBody);
        String result = body.execute().body();

    }


    /**
     * 快手-唯品会
     * @param reportDTO
     */
    private void handerKs(ReportDTO reportDTO) {

        Map<String,Object> reqParams=new HashMap<>();
        reqParams.put("event_type", "3");
        reqParams.put("event_time",reportDTO.getResultTime());
        String urlParams = URLUtil.buildQuery(reqParams, StandardCharsets.UTF_8);
        String finalReqUrl=reportDTO.getCallback()+"&"+urlParams;
        String result =  HttpUtil.createGet(finalReqUrl).execute().body();

    }


    public static String getCurrentDayBegindayStime() {
        LocalDateTime yesterdayStartingTime =getYesterdayStartingTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return formatter.format(yesterdayStartingTime);
    }

    public static LocalDateTime getYesterdayStartingTime() {
        LocalDate yesterday = LocalDate.now().minusDays(0);
        LocalTime midnight = LocalTime.MIDNIGHT;
        return LocalDateTime.of(yesterday, midnight);
    }






}
